import {
  createRouter,
  createWebHashHistory,
} from "vue-router";

import Layout from "@/layout/index.vue";
import login from "@/views/login/login.vue";
import { constantRoutes } from "./modules/routing.js";


const routes = [
  {
    path: "/home",
    component: Layout,
    children: constantRoutes
  },
  {
    path: "/login",
    name: "login",
    component: login,
  },
  {
    path: "/",
    redirect: "/login",
  },
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});
// 白名单：不需要登录就可以访问的页面
const whiteList = ['/login'];

router.beforeEach((to, from, next) => {
  // document.title = " 云晨科技-" + to.name;
  document.title = " 云晨科技";

  // 检查是否需要登录
  const userInfo = localStorage.getItem("user");
  let hasToken = false;
  
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo);
      if (user && user.user && user.user.token) {
        hasToken = true;
      }
    } catch (e) {
      // 解析失败，清理无效数据
      localStorage.removeItem("user");
    }
  }

  if (hasToken) {
    // 已经登录
    if (to.path === '/login') {
      // 如果已经登录，访问登录页，重定向到首页
      next('/home');
    } else {
      next();
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 白名单页面，直接放行
      next();
    } else {
      // 需要登录的页面，跳转到登录页
      next('/login');
    }
  }
})


export default router;
